﻿using System;
using System.Windows;
using System.Windows.Controls;
using MovieBuddy.Helpers;
using MovieBuddy.MovieUtils;
using MovieModel.Model;
using MovieModel.Model.Common;

namespace MovieBuddy.Views.MovieListView
{
    /// <summary>
    /// Interaction logic for MovieItemNoPicture.xaml
    /// </summary>
    public partial class MovieListItem
    {
        public readonly Movie Movie;
        private readonly Image image;
        private readonly EventHandler<ItemUpdatedEventArgs<MovieItem<Movie>>> movieUpdateHandler;

        public MovieListItem(Movie movie)
        {
            InitializeComponent();
            Movie = movie;
            image = new Image();

            SetFields();
            movieUpdateHandler = MovieUpdated;
            Unloaded += (sender, args) => Movie.ItemUpdated -= movieUpdateHandler;
            Movie.ItemUpdated += movieUpdateHandler;
        }

        void MovieUpdated(object sender, ItemUpdatedEventArgs<MovieItem<Movie>> e)
        {
            Dispatcher.Invoke(SetFields);
        }

        internal void SetFields()
        {
            movieTitle.Text = Movie.Name;
            descriptionArea.Text = DescriptionUtils.ShortMovieDescription(Movie);

            if (Movie.ThumbnailLocation != null)
            {
                var pic = ImageCache.GetImage(Movie.ThumbnailLocation);
                image.Source = pic;
                image.Height = 61;

                double aspectRatio = pic.Width/pic.Height;
                image.Width = (int)(image.Height * aspectRatio);

                image.HorizontalAlignment = HorizontalAlignment.Left;
                image.VerticalAlignment = VerticalAlignment.Center;
                if (!grid.Children.Contains(image)) grid.Children.Insert(0, image);
                var margin = movieTitle.Margin;
                margin.Left = image.Width + 4;
                movieTitle.Margin = margin;

                margin = descriptionArea.Margin;
                margin.Left = image.Width + 4;
                descriptionArea.Margin = margin;
            }
            else
            {
                grid.Children.Remove(image);

                var margin = movieTitle.Margin;
                margin.Left = 0;
                movieTitle.Margin = margin;

                margin = descriptionArea.Margin;
                margin.Left = 0;
                descriptionArea.Margin = margin;
            }
        }

        private bool bold = false;

        public bool Bold
        {
            get { return bold; }
            set
            {
                var fw = value ? FontWeights.Bold : FontWeights.Normal;
                Dispatcher.Invoke(new Action(() =>
                {
                    movieTitle.FontWeight = fw;
                    descriptionArea.FontWeight = fw;
                }));
                
                bold = value;
            }
        }
    }
}
